from django.shortcuts import render,redirect,HttpResponse,reverse
from app01 import models,common
from django.http import JsonResponse
from app01 import myforms
from django.contrib import auth
from django.contrib.auth.decorators import login_required
from django.db.models import Count,F
from django.db.models.functions import TruncMonth
from django.utils.safestring import mark_safe
# Create your views here.
def home(request):
    return render(request,'home.html')

def register(request):
    form_obj = myforms.MyRegForm()
    if request.method == 'POST':
        back_dic = {'code':100,'msg':''}
        # 校验用户信息是否合法
        form_obj = myforms.MyRegForm(request.POST)
        if form_obj.is_valid():
            clean_data = form_obj.cleaned_data  # clean_data = {'username':'','password':'','confirm_password':'','email':''}
            clean_data.pop('confirm_password')  # clean_data = {'username':'','password':'','email':''}
            # 手动获取用户头像
            user_file = request.FILES.get('myfile')
            if user_file:  # 一定要判断用户是否传头像了 如果传了才往字典里面添加  没传不用添加 因为有默认
                clean_data['avatar'] = user_file
            # 创建数据
            models.UserInfo.objects.create_user(**clean_data)
            back_dic['msg'] = '注册成功'
            back_dic['url'] = '/login/'
        else:
            back_dic['code'] = 101
            back_dic['msg'] = form_obj.errors
        return JsonResponse(back_dic)

    return render(request,'register.html',locals())


def login(request):
    if request.method == 'POST':
        back_dic = {'code':100,'msg':''}
        username = request.POST.get('username')
        password = request.POST.get('password')
        code = request.POST.get('code')
        # 1.先校验用户输入的验证码是否正确  忽略大小写校验 内部统一转大写或者小写比较
        if request.session.get('code').upper() == code.upper():
            # 2.数据库校验用户名和密码是否正确
            user_obj = auth.authenticate(username=username,password=password)
            if user_obj:
                # 3.保存用户登录状态
                auth.login(request,user_obj)
                back_dic['msg'] = '登录成功'
                back_dic['url'] = '/home/'
            else:
                back_dic['code'] = 101
                back_dic['msg'] = '用户名或密码错误'
        else:
            back_dic['code'] = 102
            back_dic['msg'] = '验证码错误'
        return JsonResponse(back_dic)
    return render(request,'login.html')

from PIL import Image,ImageDraw,ImageFont
"""
Image  生成图片的
ImageDraw  在图片上写东西的
ImageFont  控制字体样式的
"""
import random
from io import BytesIO,StringIO
"""
io是一个内存管理器模块
BytesIO  能够帮你存储数据 二级制格式
StringIO 能够帮你存储数据 字符串格式
"""

def get_random():
    return random.randint(0,255),random.randint(0,255),random.randint(0,255)

# 验证码相关
def get_code(request):
    # 推导步骤1:直接将本地已经存图片的以二进制方式读取发送
    # with open(r'D:\python脱产10期视频\BBS\avatar\222.jpg','rb') as f:
    #     data = f.read()
    # return HttpResponse(data)
    # 推导步骤2:能够产生任何多张的图片的方法
    # img_obj = Image.new('RGB',(35,360),'green')
    # img_obj = Image.new('RGB',(35,360),get_random())
    # # 先以文件的形式保存下来
    # with open('xxx','wb') as f:
    #     img_obj.save(f,'png')
    # # 然后再打开这个文件发送
    # with open('xxx','rb') as f:
    #     data = f.read()
    # return HttpResponse(data)
    # 推导步骤3:需要找一个能够临时存储文件的地方  避免频繁文件读写操作
    # img_obj = Image.new('RGB', (35, 360), get_random())
    # io_obj = BytesIO()  # 实例化产生一个内存管理对象  你可以把它当成文件句柄
    # img_obj.save(io_obj,'png')
    # return HttpResponse(io_obj.getvalue())  # 从内存对象中获取二级制的图片数据
    # 推导步骤4:在产生的图片上 写验证码
    img_obj = Image.new('RGB', (360,35), get_random())
    img_draw = ImageDraw.Draw(img_obj)  # 生成一个可以在图片上写字的画笔对象
    img_font = ImageFont.truetype('static/font/222.ttf',30)  # 字体样式 及 大小
    io_obj = BytesIO()
    # 图片验证码 一般都是有 数字  大写字母  小写字母
    # 五位  每一位都可以 数字或大写字母或小写字母
    code = ''
    for i in range(5):
        upper_str = chr(random.randint(65,90))
        low_str = chr(random.randint(97,122))
        random_int = str(random.randint(0,9))
        # 随机取一个
        temp_code = random.choice([upper_str,low_str,random_int])
        # 朝图片上写
        img_draw.text((70+i*45,0),temp_code,get_random(),font=img_font)
        code += temp_code
    print(code)
    # 将产生的随机验证码 存入session中 以便后续其他视图函数获取 校验验证码
    request.session['code'] = code
    img_obj.save(io_obj,'png')
    return HttpResponse(io_obj.getvalue())
@login_required
def logout(request):
    auth.logout(request)
    return redirect('/login/')

@login_required
def set_password(request):
    if request.is_ajax():
        back_dic = {'code':100,'msg':''}
        old_password = request.POST.get('old_password')
        new_password = request.POST.get('new_password')
        confirm_password = request.POST.get('confirm_password')
        is_right = request.user.check_password(old_password)
        if is_right:
            if new_password == confirm_password:
                request.user.set_password(new_password)
                request.user.save()
                back_dic['msg'] = '修改成功'
                back_dic['url'] = '/login/'
            else:
                back_dic['code'] = 102
                back_dic['msg'] = '两次密码不一致'
        else:
            back_dic['code'] = 101
            back_dic['msg'] = '原密码错误'

        return JsonResponse(back_dic)

# 查询赊账记录
@login_required
def book_list(request):
    # 查询赊账表中所有的记录
    book_queryset = models.ToMoney.objects.filter(is_delete=0).all()
    return render(request,'book_list.html',locals())
# 赊账新增
@login_required
def add_book(request):
    if request.method == 'POST':
        # 获取用户提交的数据
        name = request.POST.get('name')
        money = request.POST.get('money')
        path = request.POST.get('path')
        telephone = request.POST.get('telephone')
        ps = request.POST.get('ps')
        register_time = common.get_nowtime()
        # 将数据保存到数据库
        book_obj = models.ToMoney.objects.create(name=name,money=money,path=path,ps=ps,is_delete=0,telephone=telephone,register_time=register_time)
        add_money = 0
        sum_money = money
        book_obj = models.AddMoney.objects.create(name=name, add_money=add_money,sum_money=sum_money, path=path, ps=ps, is_delete=0, telephone=telephone, register_time=register_time)
        print(book_obj)
        # 重定向到书籍展示页
        print(456)
        return redirect(reverse('list'))
    # 给用户返回一个可以输入的添加页面
    return render(request,'add_book.html',locals())

def delete_book(request,delete_id):
    register_time = common.get_nowtime()
    models.ToMoney.objects.filter(pk=delete_id).update(is_delete=1,register_time=register_time)
    return redirect(reverse('list'))

@login_required
def edit_book(request,edit_id):
    # 编辑是基于已经有了的数据 进行一个修改操作
    # 获取用户想要编辑的数据对象
    edit_obj = models.ToMoney.objects.filter(pk=edit_id)[0]
    print(edit_obj,11111111)
    money = edit_obj.money
    print(money,2000)
    if request.method == 'POST':
        # 获取用户修改完的数据
        name = request.POST.get('name')
        money += int(request.POST.get('money'))
        edit_obj1 = models.AddMoney.objects.filter(name=name)[0]
        sum_money = edit_obj1.sum_money
        sum_money += edit_obj.money
        path = request.POST.get('path')
        telephone = request.POST.get('telephone')
        ps = request.POST.get('ps')
        register_time = common.get_nowtime()
        models.ToMoney.objects.filter(pk=edit_id).update(name=name,money=money,path=path,ps=ps,is_delete=0,telephone=telephone,register_time=register_time)
        edit_obj = models.AddMoney.objects.filter(name=name)[0]
        add_money = edit_obj.add_money
        print(add_money,'add_money')
        models.AddMoney.objects.filter(name=name).update(name=name, add_money=add_money,sum_money=sum_money, path=path, ps=ps, is_delete=0,telephone=telephone, register_time=register_time)
        # 重定向到展示页面
        return redirect(reverse('list'))
    # 将用户想要编辑的数据 展示到前端 供用户修改
    # 还需要将网站所有的出版社和作者传递给前端展示
    money_list = models.ToMoney.objects.all()
    return render(request,'edit_book.html',locals())


# 查询还款记录
@login_required
def book_1_list(request):
    # 查询赊账表中所有的记录
    book_queryset = models.AddMoney.objects.filter(is_delete=0).all()
    return render(request,'book1_list.html',locals())

@login_required
def add_book1(request):
    if request.method == 'POST':
        # 获取用户提交的数据
        name = request.POST.get('name')
        money = request.POST.get('money')
        add_money = request.POST.get('add_money')
        sum_money = request.POST.get('sum_money')
        path = request.POST.get('path')
        telephone = request.POST.get('telephone')
        ps = request.POST.get('ps')
        register_time = common.get_nowtime()
        # 将数据保存到数据库
        book_obj = models.AddMoney.objects.create(name=name,sum_money=sum_money,add_money=add_money,path=path,ps=ps,is_delete=0,telephone=telephone,register_time=register_time)
        print(book_obj)
        # 重定向到书籍展示页
        print(456)
        return redirect(reverse('list1'))
    # 给用户返回一个可以输入的添加页面
    print('123')
    return render(request,'add1_book.html',locals())

@login_required
def delete_book1(request,delete_id):
    register_time = common.get_nowtime()
    models.AddMoney.objects.filter(pk=delete_id).update(is_delete=1, register_time=register_time)
    return redirect(reverse('list1'))

def to_money(request,name,money,delete_id):
    money = int(money)
    edit_obj = models.ToMoney.objects.filter(name=name)[0]
    money = edit_obj.money - money
    register_time = common.get_nowtime()
    if money >= 0:
        if money < 0:
            return redirect(reverse('list1'))
        elif money == 0:
            delete_book1(request,delete_id)
            models.ToMoney.objects.filter(name=name).update(register_time=register_time, is_delete=1, money=money)
        models.ToMoney.objects.filter(name=name).update(register_time=register_time,money=money)
    else:
        return redirect(reverse('list1'))


@login_required
def edit_book1(request,edit_id):
    # 编辑是基于已经有了的数据 进行一个修改操作
    # 获取用户想要编辑的数据对象
    edit_obj = models.AddMoney.objects.filter(pk=edit_id).first()
    if request.method == 'POST':
        # 获取用户修改完的数据
        name = request.POST.get('name')
        money = request.POST.get('money')
        delete_id = edit_id
        to_money(request,name,money,delete_id)
        edit_obj = models.AddMoney.objects.filter(pk=edit_id)[0]
        add_money = edit_obj.add_money
        sum_money = edit_obj.sum_money
        add_money = add_money + int(money)
        path = request.POST.get('path')
        telephone = request.POST.get('telephone')
        ps = request.POST.get('ps')
        register_time = common.get_nowtime()
        if add_money <= sum_money:
            models.AddMoney.objects.filter(pk=edit_id).update(name=name,add_money=add_money,path=path,ps=ps,is_delete=0,telephone=telephone,register_time=register_time)
            if add_money == sum_money:
                models.AddMoney.objects.filter(pk=edit_id).update(name=name, add_money=add_money, path=path, ps=ps,is_delete=1, telephone=telephone,register_time=register_time)
                models.SeMoney.objects.filter(pk=edit_id).create(name=name, add_money=add_money, sum_money=sum_money,path=path, ps=ps,
                                                                  is_delete=0, telephone=telephone,
                                                                  register_time=register_time)
        # 重定向到展示页面
        return redirect(reverse('list1'))
    # 将用户想要编辑的数据 展示到前端 供用户修改
    # 还需要将网站所有的出版社和作者传递给前端展示
    money_list = models.ToMoney.objects.all()
    return render(request,'edit1_book.html',locals())





# 查询赊账结清记录
@login_required
def book_2_list(request):
    # 查询赊账表中所有的记录
    book_queryset = models.SeMoney.objects.filter(is_delete=0).all()
    return render(request,'book2_list.html',locals())

def add_book2(request):
    if request.method == 'POST':
        # 获取用户提交的数据
        name = request.POST.get('name')
        add_money = request.POST.get('add_money')
        sum_money = request.POST.get('sum_money')
        path = request.POST.get('path')
        telephone = request.POST.get('telephone')
        ps = request.POST.get('ps')
        register_time = common.get_nowtime()
        # 将数据保存到数据库
        book_obj = models.SeMoney.objects.create(name=name,sum_money=sum_money,add_money=add_money,path=path,ps=ps,is_delete=0,telephone=telephone,register_time=register_time)
        print(book_obj)
        # 重定向到书籍展示页
        print(456)
        return redirect(reverse('list2'))
    # 给用户返回一个可以输入的添加页面
    print('123')
    return render(request,'add1_book.html',locals())

@login_required
def delete_book2(request,delete_id):
    register_time = common.get_nowtime()
    models.SeMoney.objects.filter(pk=delete_id).update(is_delete=1, register_time=register_time)
    return redirect(reverse('list2'))

@login_required
def edit_book2(request,edit_id):
    # 编辑是基于已经有了的数据 进行一个修改操作
    # 获取用户想要编辑的数据对象
    edit_obj = models.SeMoney.objects.filter(pk=edit_id).first()
    if request.method == 'POST':
        # 获取用户修改完的数据
        name = request.POST.get('name')
        add_money = request.POST.get('add_money')
        sum_money = request.POST.get('sum_money')
        path = request.POST.get('path')
        telephone = request.POST.get('telephone')
        ps = request.POST.get('ps')
        register_time = common.get_nowtime()
        models.SeMoney.objects.filter(pk=edit_id).update(name=name,sum_money=sum_money,add_money=add_money,path=path,ps=ps,is_delete=0,telephone=telephone,register_time=register_time)
        # 重定向到展示页面
        return redirect(reverse('list2'))
    # 将用户想要编辑的数据 展示到前端 供用户修改
    # 还需要将网站所有的出版社和作者传递给前端展示
    money_list = models.ToMoney.objects.all()
    return render(request,'edit2_book.html',locals())